<template>
  <view class="history-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">情绪历史</text>
      </view>
      <view class="navbar-action" @tap="showFilterModal">
        <text class="action-text">筛选</text>
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-card">
      <view class="stats-item">
        <text class="stats-number">{{ totalRecords }}</text>
        <text class="stats-label">总记录</text>
      </view>
      <view class="stats-item">
        <text class="stats-number">{{ continuousDays }}</text>
        <text class="stats-label">连续天数</text>
      </view>
      <view class="stats-item">
        <text class="stats-number">{{ averageMood }}</text>
        <text class="stats-label">平均心情</text>
      </view>
    </view>

    <!-- 时间筛选 -->
    <view class="filter-tabs">
      <view 
        class="filter-tab" 
        :class="{ active: activeFilter === filter.key }"
        v-for="filter in filterOptions" 
        :key="filter.key"
        @tap="changeFilter(filter.key)"
      >
        <text class="filter-text">{{ filter.label }}</text>
      </view>
    </view>

    <!-- 情绪记录列表 -->
    <view class="records-container">
      <view v-if="filteredRecords.length === 0" class="empty-state">
        <text class="empty-icon">📝</text>
        <text class="empty-title">暂无记录</text>
        <text class="empty-desc">开始记录你的情绪变化吧</text>
        <view class="empty-action" @tap="addMoodRecord">
          <text class="action-btn-text">添加记录</text>
        </view>
      </view>

      <view v-else class="records-list">
        <view class="date-group" v-for="group in groupedRecords" :key="group.date">
          <view class="date-header">
            <text class="date-text">{{ formatDate(group.date) }}</text>
            <text class="date-count">{{ group.records.length }}条记录</text>
          </view>
          
          <view class="record-item" v-for="record in group.records" :key="record.id" @tap="viewRecord(record)">
            <view class="record-mood">
              <text class="mood-emoji">{{ getMoodEmoji(record.mood) }}</text>
              <view class="mood-info">
                <text class="mood-name">{{ record.mood }}</text>
                <text class="mood-intensity">强度: {{ record.intensity }}/10</text>
              </view>
            </view>
            
            <view class="record-content">
              <text class="record-time">{{ formatTime(record.createTime) }}</text>
              <text class="record-text" v-if="record.content">{{ record.content }}</text>
              
              <view class="record-tags" v-if="record.tags && record.tags.length > 0">
                <text class="tag" v-for="tag in record.tags.slice(0, 3)" :key="tag">{{ tag }}</text>
                <text class="tag-more" v-if="record.tags.length > 3">+{{ record.tags.length - 3 }}</text>
              </view>
            </view>
            
            <view class="record-actions">
              <text class="action-icon" @tap.stop="editRecord(record)">✏️</text>
              <text class="action-icon" @tap.stop="deleteRecord(record)">🗑️</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选弹窗 -->
    <view class="modal-overlay" v-if="showFilter" @tap="hideFilterModal">
      <view class="filter-modal" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">筛选条件</text>
          <text class="modal-close" @tap="hideFilterModal">×</text>
        </view>
        
        <view class="filter-section">
          <text class="section-title">心情类型</text>
          <view class="mood-filters">
            <view 
              class="mood-filter" 
              :class="{ active: selectedMoods.includes(mood.key) }"
              v-for="mood in moodTypes" 
              :key="mood.key"
              @tap="toggleMoodFilter(mood.key)"
            >
              <text class="mood-emoji">{{ mood.emoji }}</text>
              <text class="mood-name">{{ mood.name }}</text>
            </view>
          </view>
        </view>
        
        <view class="filter-section">
          <text class="section-title">强度范围</text>
          <view class="intensity-range">
            <slider 
              :value="intensityRange[0]" 
              min="1" 
              max="10" 
              @change="updateIntensityMin"
              activeColor="#667eea"
            />
            <text class="range-text">{{ intensityRange[0] }} - {{ intensityRange[1] }}</text>
            <slider 
              :value="intensityRange[1]" 
              min="1" 
              max="10" 
              @change="updateIntensityMax"
              activeColor="#667eea"
            />
          </view>
        </view>
        
        <view class="modal-actions">
          <view class="modal-btn reset" @tap="resetFilter">
            <text class="btn-text">重置</text>
          </view>
          <view class="modal-btn confirm" @tap="applyFilter">
            <text class="btn-text">确定</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 记录详情弹窗 -->
    <view class="modal-overlay" v-if="selectedRecord" @tap="hideRecordDetail">
      <view class="record-detail-modal" @tap.stop>
        <view class="modal-header">
          <text class="modal-title">记录详情</text>
          <text class="modal-close" @tap="hideRecordDetail">×</text>
        </view>
        
        <view class="detail-content">
          <view class="detail-mood">
            <text class="detail-emoji">{{ getMoodEmoji(selectedRecord.mood) }}</text>
            <view class="detail-info">
              <text class="detail-name">{{ selectedRecord.mood }}</text>
              <text class="detail-time">{{ formatDateTime(selectedRecord.createTime) }}</text>
            </view>
          </view>
          
          <view class="detail-intensity">
            <text class="detail-label">情绪强度</text>
            <view class="intensity-bar">
              <view class="intensity-fill" :style="{ width: (selectedRecord.intensity * 10) + '%' }"></view>
            </view>
            <text class="intensity-value">{{ selectedRecord.intensity }}/10</text>
          </view>
          
          <view class="detail-tags" v-if="selectedRecord.tags && selectedRecord.tags.length > 0">
            <text class="detail-label">情绪标签</text>
            <view class="tags-list">
              <text class="detail-tag" v-for="tag in selectedRecord.tags" :key="tag">{{ tag }}</text>
            </view>
          </view>
          
          <view class="detail-content-text" v-if="selectedRecord.content">
            <text class="detail-label">记录内容</text>
            <text class="content-text">{{ selectedRecord.content }}</text>
          </view>
        </view>
        
        <view class="detail-actions">
          <view class="detail-btn edit" @tap="editRecord(selectedRecord)">
            <text class="btn-text">编辑</text>
          </view>
          <view class="detail-btn delete" @tap="deleteRecord(selectedRecord)">
            <text class="btn-text">删除</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      records: [],
      activeFilter: 'all',
      showFilter: false,
      selectedRecord: null,
      selectedMoods: [],
      intensityRange: [1, 10],
      filterOptions: [
        { key: 'all', label: '全部' },
        { key: 'today', label: '今天' },
        { key: 'week', label: '本周' },
        { key: 'month', label: '本月' }
      ],
      moodTypes: [
        { key: '开心', name: '开心', emoji: '😊' },
        { key: '平静', name: '平静', emoji: '😌' },
        { key: '焦虑', name: '焦虑', emoji: '😰' },
        { key: '难过', name: '难过', emoji: '😢' },
        { key: '愤怒', name: '愤怒', emoji: '😠' },
        { key: '兴奋', name: '兴奋', emoji: '🤩' },
        { key: '疲惫', name: '疲惫', emoji: '😴' },
        { key: '困惑', name: '困惑', emoji: '😕' }
      ]
    }
  },
  
  computed: {
    totalRecords() {
      return this.records.length
    },
    
    continuousDays() {
      if (this.records.length === 0) return 0
      
      const dates = [...new Set(this.records.map(record => 
        new Date(record.createTime).toDateString()
      ))].sort((a, b) => new Date(b) - new Date(a))
      
      let continuous = 1
      const today = new Date().toDateString()
      
      if (dates[0] !== today) return 0
      
      for (let i = 1; i < dates.length; i++) {
        const current = new Date(dates[i])
        const previous = new Date(dates[i - 1])
        const diffTime = previous - current
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        
        if (diffDays === 1) {
          continuous++
        } else {
          break
        }
      }
      
      return continuous
    },
    
    averageMood() {
      if (this.records.length === 0) return '0.0'
      const total = this.records.reduce((sum, record) => sum + record.intensity, 0)
      return (total / this.records.length).toFixed(1)
    },
    
    filteredRecords() {
      let filtered = [...this.records]
      
      // 时间筛选
      const now = new Date()
      switch (this.activeFilter) {
        case 'today':
          filtered = filtered.filter(record => {
            const recordDate = new Date(record.createTime)
            return recordDate.toDateString() === now.toDateString()
          })
          break
        case 'week':
          const weekStart = new Date(now.setDate(now.getDate() - now.getDay()))
          filtered = filtered.filter(record => new Date(record.createTime) >= weekStart)
          break
        case 'month':
          const monthStart = new Date(now.getFullYear(), now.getMonth(), 1)
          filtered = filtered.filter(record => new Date(record.createTime) >= monthStart)
          break
      }
      
      // 心情筛选
      if (this.selectedMoods.length > 0) {
        filtered = filtered.filter(record => this.selectedMoods.includes(record.mood))
      }
      
      // 强度筛选
      filtered = filtered.filter(record => 
        record.intensity >= this.intensityRange[0] && 
        record.intensity <= this.intensityRange[1]
      )
      
      return filtered.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
    },
    
    groupedRecords() {
      const groups = {}
      
      this.filteredRecords.forEach(record => {
        const date = new Date(record.createTime).toDateString()
        if (!groups[date]) {
          groups[date] = []
        }
        groups[date].push(record)
      })
      
      return Object.keys(groups)
        .sort((a, b) => new Date(b) - new Date(a))
        .map(date => ({
          date,
          records: groups[date].sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        }))
    }
  },
  
  onLoad() {
    this.loadRecords()
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    loadRecords() {
      try {
        const records = uni.getStorageSync('mood_records') || []
        this.records = records
      } catch (e) {
        console.error('加载记录失败:', e)
        this.records = []
      }
    },
    
    changeFilter(filterKey) {
      this.activeFilter = filterKey
    },
    
    showFilterModal() {
      this.showFilter = true
    },
    
    hideFilterModal() {
      this.showFilter = false
    },
    
    toggleMoodFilter(mood) {
      const index = this.selectedMoods.indexOf(mood)
      if (index > -1) {
        this.selectedMoods.splice(index, 1)
      } else {
        this.selectedMoods.push(mood)
      }
    },
    
    updateIntensityMin(e) {
      this.intensityRange[0] = e.detail.value
      if (this.intensityRange[0] > this.intensityRange[1]) {
        this.intensityRange[1] = this.intensityRange[0]
      }
    },
    
    updateIntensityMax(e) {
      this.intensityRange[1] = e.detail.value
      if (this.intensityRange[1] < this.intensityRange[0]) {
        this.intensityRange[0] = this.intensityRange[1]
      }
    },
    
    resetFilter() {
      this.selectedMoods = []
      this.intensityRange = [1, 10]
    },
    
    applyFilter() {
      this.hideFilterModal()
    },
    
    viewRecord(record) {
      this.selectedRecord = record
    },
    
    hideRecordDetail() {
      this.selectedRecord = null
    },
    
    editRecord(record) {
      this.hideRecordDetail()
      uni.navigateTo({
        url: `/pages/mood/add?id=${record.id}`
      })
    },
    
    deleteRecord(record) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这条情绪记录吗？',
        success: (res) => {
          if (res.confirm) {
            this.confirmDelete(record)
          }
        }
      })
    },
    
    confirmDelete(record) {
      try {
        let records = uni.getStorageSync('mood_records') || []
        records = records.filter(item => item.id !== record.id)
        uni.setStorageSync('mood_records', records)
        
        this.loadRecords()
        this.hideRecordDetail()
        
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      } catch (e) {
        console.error('删除记录失败:', e)
        uni.showToast({
          title: '删除失败',
          icon: 'error'
        })
      }
    },
    
    addMoodRecord() {
      uni.navigateTo({
        url: '/pages/mood/add'
      })
    },
    
    getMoodEmoji(mood) {
      const moodType = this.moodTypes.find(type => type.key === mood)
      return moodType ? moodType.emoji : '😊'
    },
    
    formatDate(dateString) {
      const date = new Date(dateString)
      const today = new Date()
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      
      if (date.toDateString() === today.toDateString()) {
        return '今天'
      } else if (date.toDateString() === yesterday.toDateString()) {
        return '昨天'
      } else {
        return `${date.getMonth() + 1}月${date.getDate()}日`
      }
    },
    
    formatTime(dateString) {
      const date = new Date(dateString)
      return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
    },
    
    formatDateTime(dateString) {
      const date = new Date(dateString)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${this.formatTime(dateString)}`
    }
  }
}
</script>

<style scoped>
.history-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

/* 导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
}

.navbar-action {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-text {
  font-size: 28rpx;
}

/* 统计卡片 */
.stats-card {
  background: white;
  margin: 30rpx;
  padding: 40rpx;
  border-radius: 20rpx;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.stats-item {
  text-align: center;
}

.stats-number {
  display: block;
  font-size: 48rpx;
  font-weight: 700;
  color: var(--primary-color);
  margin-bottom: 10rpx;
}

.stats-label {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

/* 筛选标签 */
.filter-tabs {
  display: flex;
  padding: 0 30rpx 20rpx;
  gap: 20rpx;
}

.filter-tab {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  background: white;
  border-radius: 25rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.filter-tab.active {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
}

.filter-text {
  font-size: 28rpx;
  color: var(--text-secondary);
}

.filter-tab.active .filter-text {
  color: white;
  font-weight: 600;
}

/* 记录列表 */
.records-container {
  padding: 0 30rpx 30rpx;
}

.empty-state {
  text-align: center;
  padding: 100rpx 40rpx;
  background: white;
  border-radius: 20rpx;
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.08);
}

.empty-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 15rpx;
}

.empty-desc {
  font-size: 28rpx;
  color: var(--text-secondary);
  display: block;
  margin-bottom: 40rpx;
}

.empty-action {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  padding: 24rpx 48rpx;
  border-radius: 25rpx;
  display: inline-block;
}

.action-btn-text {
  color: white;
  font-size: 28rpx;
  font-weight: 600;
}

.date-group {
  margin-bottom: 40rpx;
}

.date-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 2rpx solid var(--border-color);
  margin-bottom: 20rpx;
}

.date-text {
  font-size: 32rpx;
  font-weight: 600;
  color: var(--text-primary);
}

.date-count {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.record-item {
  background: white;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05);
}

.record-mood {
  display: flex;
  align-items: center;
  gap: 15rpx;
  min-width: 160rpx;
}

.mood-emoji {
  font-size: 48rpx;
}

.mood-info {
  display: flex;
  flex-direction: column;
}

.mood-name {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 5rpx;
}

.mood-intensity {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.record-content {
  flex: 1;
}

.record-time {
  font-size: 24rpx;
  color: var(--text-tertiary);
  display: block;
  margin-bottom: 10rpx;
}

.record-text {
  font-size: 28rpx;
  color: var(--text-secondary);
  line-height: 1.5;
  display: block;
  margin-bottom: 15rpx;
}

.record-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.tag {
  background: var(--accent-color);
  color: var(--primary-color);
  padding: 8rpx 16rpx;
  border-radius: 12rpx;
  font-size: 24rpx;
}

.tag-more {
  color: var(--text-tertiary);
  font-size: 24rpx;
  padding: 8rpx 0;
}

.record-actions {
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.action-icon {
  font-size: 32rpx;
  padding: 10rpx;
}

/* 筛选弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.filter-modal {
  background: white;
  width: 90%;
  max-width: 600rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.modal-header {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  padding: 40rpx;
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 600;
}

.modal-close {
  font-size: 48rpx;
  font-weight: 300;
}

.filter-section {
  padding: 40rpx;
  border-bottom: 2rpx solid var(--border-color);
}

.section-title {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 20rpx;
}

.mood-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.mood-filter {
  display: flex;
  align-items: center;
  gap: 10rpx;
  padding: 15rpx 20rpx;
  border: 2rpx solid var(--border-color);
  border-radius: 25rpx;
  background: white;
}

.mood-filter.active {
  border-color: var(--primary-color);
  background: var(--accent-color);
}

.mood-filter .mood-emoji {
  font-size: 32rpx;
}

.mood-filter .mood-name {
  font-size: 26rpx;
  color: var(--text-secondary);
}

.mood-filter.active .mood-name {
  color: var(--primary-color);
  font-weight: 600;
}

.intensity-range {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.range-text {
  text-align: center;
  font-size: 28rpx;
  color: var(--text-primary);
  font-weight: 600;
}

.modal-actions {
  padding: 40rpx;
  display: flex;
  gap: 20rpx;
}

.modal-btn {
  flex: 1;
  text-align: center;
  padding: 24rpx;
  border-radius: 12rpx;
}

.modal-btn.reset {
  background: var(--border-color);
}

.modal-btn.confirm {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
}

.modal-btn.reset .btn-text {
  color: var(--text-secondary);
}

.modal-btn.confirm .btn-text {
  color: white;
  font-weight: 600;
}

/* 记录详情弹窗 */
.record-detail-modal {
  background: white;
  width: 90%;
  max-width: 600rpx;
  border-radius: 20rpx;
  overflow: hidden;
  max-height: 80vh;
}

.detail-content {
  padding: 40rpx;
  max-height: 60vh;
  overflow-y: auto;
}

.detail-mood {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.detail-emoji {
  font-size: 80rpx;
}

.detail-info {
  flex: 1;
}

.detail-name {
  font-size: 36rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 10rpx;
}

.detail-time {
  font-size: 26rpx;
  color: var(--text-tertiary);
}

.detail-intensity {
  margin-bottom: 30rpx;
}

.detail-label {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--text-primary);
  display: block;
  margin-bottom: 15rpx;
}

.intensity-bar {
  height: 12rpx;
  background: var(--border-color);
  border-radius: 6rpx;
  overflow: hidden;
  margin-bottom: 10rpx;
}

.intensity-fill {
  height: 100%;
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
}

.intensity-value {
  font-size: 26rpx;
  color: var(--text-secondary);
}

.detail-tags {
  margin-bottom: 30rpx;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.detail-tag {
  background: var(--accent-color);
  color: var(--primary-color);
  padding: 10rpx 20rpx;
  border-radius: 15rpx;
  font-size: 26rpx;
}

.detail-content-text {
  margin-bottom: 30rpx;
}

.content-text {
  font-size: 28rpx;
  color: var(--text-secondary);
  line-height: 1.6;
  background: var(--background-light);
  padding: 20rpx;
  border-radius: 12rpx;
}

.detail-actions {
  padding: 40rpx;
  display: flex;
  gap: 20rpx;
  border-top: 2rpx solid var(--border-color);
}

.detail-btn {
  flex: 1;
  text-align: center;
  padding: 24rpx;
  border-radius: 12rpx;
}

.detail-btn.edit {
  background: var(--accent-color);
}

.detail-btn.delete {
  background: #ffebee;
}

.detail-btn.edit .btn-text {
  color: var(--primary-color);
  font-weight: 600;
}

.detail-btn.delete .btn-text {
  color: #f44336;
  font-weight: 600;
}
</style>